<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/
namespace app\admin\controller\merchant;

use app\admin\model\Level;
use app\admin\model\merchant\Image;
use app\admin\model\merchant\StoreInfo;
use app\admin\model\User;
use app\common\controller\BackendApi;
use app\common\library\InviteCode;
use app\common\library\Map\Map;
use app\common\model\Region;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商户店铺管理
 *
 * @icon fa fa-circle-o
 */
class Store extends BackendApi
{

    /**
     * Store模型对象
     * @var \app\admin\model\merchant\Store
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\merchant\Store;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("organizeableList", $this->model->getOrganizeableList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        if (!$list->isEmpty()) {
            foreach ($list as &$row) {
                if ($row->level) {
                    $row->level_name = Level::where('vl_id', $row->level)->value('vip_name') ?? '';
                }
            }
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    public function add(){
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if (empty($params['address']) || empty($params['long']) || empty($params['lat'])) {
            $this->error('地址不能为空，请从地图选择店铺对应的位置');
        }

        $addressConfig = get_addon_config('address');
        $map = new Map($addressConfig);
        $location = $params['lat'].','.$params['long'];
        $map->getInfoByLocation($location);
        $response = $map->getResponse();
        $response = json_decode($response, true);
        $mobileInfo = User::where('mobile',$params['mobile'])->find();
        if (!empty($response) && isset($response['status']) && $response['status'] == 0 && isset($response['result']) && isset($response['result']['address_component'])) {
            $province = $response['result']['address_component']['province'] ?: '';
            $city = $response['result']['address_component']['city'] ?: '';
            $district = $response['result']['address_component']['district'] ?: '';
            $params['province'] = Region::where('name',$province)->value('city_code');
            $params['city'] = Region::where('name',$city)->value('city_code');
            $params['district'] = Region::where('name',$district)->value('city_code');
            $params['user_id'] = $mobileInfo['id'] ?? 0;
        }
        $result = false;
        Db::startTrans();
        try {

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $inviteCode = new InviteCode();
            $invite = $inviteCode->enCode();

            $params['invite_code'] = $invite;
            $image = [];
            if ($params['banner_image']){
                $image = explode(',',$params['banner_image']);
                unset($params['banner_image']);
            }
            $result = $this->model->allowField(true)->save($params);
            $id = $this->model->getLastInsID();
            /**
             * 写入店铺账户信息
             */
            \app\admin\model\merchant\StoreAccount::create([
                'merchant_id'=>$params['merchant_id'],
                'store_id'=>$id
            ]);
            /**
             * 如果当前店长账号存在，插入店铺关系数据，修改店长账号属性
             */
            if (!empty($params['mobile']) && $mobileInfo) {
                StoreInfo::create([
                    'merchant_id' => $params['merchant_id'],
                    'store_id' => $id,
                    'is_manager' => StoreInfo::IS_MANAGER,
                    'user_id' => $mobileInfo['id'],
                    'create_time' => time(),
                ]);
                User::where('mobile', $params['mobile'])->update(['is_store'=>\app\common\model\User::IS_STORE_YES,'is_merchant'=>\app\common\model\User::IS_MERCHANT_YES,'merchant_id'=>$params['merchant_id']]);
            }

            if ($image){
                foreach ($image as $v){
                    $imageInsert[] = [
                        'merchant_id'=>$params['merchant_id'],
                        'store_id'=>$id,
                        'url'=>$v,
                        'created_time'=>time(),
                    ];
                }
                if ($imageInsert){
                    $imageModel = new \app\admin\model\store\Image();
                    $imageModel->saveAll($imageInsert);
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $info = \app\admin\model\store\Image::where('store_id',$row->id)->select();
        $imageArr = [];
        if ($info){
            foreach ($info as $v){
                $imageArr[] = $v->url;
            }
        }
        $row->banner_image = $imageArr ? implode(',',$imageArr) : '';

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if (empty($params['address']) || empty($params['long']) || empty($params['lat'])) {
            $this->error('地址不能为空，请从地图选择店铺对应的位置');
        }

        $addressConfig = get_addon_config('address');
        $map = new Map($addressConfig);
        $location = $params['lat'].','.$params['long'];
        $map->getInfoByLocation($location);
        $response = $map->getResponse();
        $response = json_decode($response, true);
        $mobileInfo = User::where('mobile',$row->mobile)->find();
        $mobileInfoNew = User::where('mobile',$params['mobile'])->find();
        if (!empty($response) && isset($response['status']) && $response['status'] == 0 && isset($response['result']) && isset($response['result']['address_component'])) {
            $province = $response['result']['address_component']['province'] ?: '';
            $city = $response['result']['address_component']['city'] ?: '';
            $district = $response['result']['address_component']['district'] ?: '';
            $params['province'] = Region::where('name',$province)->value('city_code');
            $params['city'] = Region::where('name',$city)->value('city_code');
            $params['district'] = Region::where('name',$district)->value('city_code');
            $params['user_id'] = $mobileInfoNew['id'] ?? 0;
        }
        $result = false;
        Db::startTrans();
        try {

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $image = [];
            if ($params['banner_image']){
                $image = explode(',',$params['banner_image']);
                unset($params['banner_image']);
            }


            $result = $row->allowField(true)->save($params);

            if ($image){
                foreach ($image as $v){
                    $imageInsert[] = [
                        'merchant_id'=>$row->merchant_id,
                        'store_id'=>$row->id,
                        'url'=>$v,
                        'created_time'=>time(),
                    ];
                }
                if ($imageInsert){
                    $imageModel = new \app\admin\model\store\Image();
                    $imageModel->where('merchant_id',$row->merchant_id)->where('store_id',$row->id)->delete();
                    $imageModel->saveAll($imageInsert);
                }
            }
            /**
             * 更换门店店长用户
             * 1、删除原店长用户店长属性
             * 2、删除原店长用户绑定记录
             * 3、添加现店长用户店长属性
             * 4、添加现店长用户店长绑定记录
             */
            if ($row->mobile != $params['mobile'] ) {

                /**
                 * 1、删除原店长用户店长属性
                 * 2、删除原店长用户绑定记录
                 */
                if ($mobileInfo){

                    StoreInfo::where([
                        'store_id' => $row->id,
                        'user_id' => $mobileInfo['id'],
                    ])->delete();

                    if (StoreInfo::where('user_id',$mobileInfo['id'])->where('store_id','>',0)->count() <=1){
                        User::where('mobile',$row->mobile)->update(['is_store'=>\app\common\model\User::IS_STORE_NO,'merchant_id'=> 0]);
                    }

                }


                /**
                 *  3、添加现店长用户店长属性
                 *  4、添加现店长用户店长绑定记录
                 */
                if ($mobileInfoNew) {

                    StoreInfo::create([
                        'merchant_id' => $row->merchant_id,
                        'store_id' => $row->id,
                        'is_manager' => StoreInfo::IS_MANAGER,
                        'user_id' => $mobileInfoNew['id'],
                        'create_time' => time(),
                    ]);

                    User::where('mobile', $params['mobile'])->update(['is_store'=>\app\common\model\User::IS_STORE_YES,'is_merchant'=>\app\common\model\User::IS_MERCHANT_YES,'merchant_id'=>$row->merchant_id]);
                }

            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function del($ids = null){
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
                if ($mobileInfo = User::where('mobile',$item->mobile)->find()) {

                    if (StoreInfo::where('user_id',$mobileInfo['id'])->where('store_id','>',0)->count() <= 1) {
                        User::where('mobile',$item->mobile)->update(['is_store'=>\app\common\model\User::IS_STORE_NO]);
                    }

                    StoreInfo::where('store_id',$item->id)->where('user_id',$mobileInfo['id'])->delete();
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
